define(['util', 'ajax'], function (util, ajax) {
    "use strict";

    var exports = {},
		ViewModel, Contact;

    Contact = function (data) {
        var self = this;

        self.id = ko.observable(data.id);
        self.name = ko.observable(data.name);
        self.nameTitle = ko.observable(data.nameTitle);
        self.firstName = ko.observable(data.firstName);
        self.lastName = ko.observable(data.lastName);
        self.email = ko.observable(data.email).revertable();
        self.phone = ko.observable(data.phone);
        self.mobile = ko.observable(data.mobile).revertable();
        self.companyName = ko.observable(data.companyName);
        self.designation = ko.observable(data.designation);
        self.description = ko.observable(data.description);
        self.fullName = ko.computed(function () {
            return self.nameTitle() + " " + self.lastName() +" " + self.firstName();
        }, this);
    };

    ViewModel = function (model, inPicker) {
        var self = this;

        self.contacts = ko.observableArray(ko.utils.arrayMap(model.items, function (item) {
            return new Contact(item);
        }));

        console.log(self.contacts());

        self.deleteRecord = function (record) {
            if (!confirm("Are you sure you want to delete this record?")) return;
            ajax.del('contact', record.id(), { async: false })
                .done(function () { self.search(); });
        };

        self.startDownload = function () {
            if (!self.filterColumn()) self.filterColumn('Code');
            if (!self.filterValue()) self.filterValue('%');
            if (self.pageIndex() <= 0) self.pageIndex(1);
            if (self.pageIndex() > self.totalPages()) self.pageIndex(self.totalPages());
            if (self.pageSize() < 25) self.pageSize(25);
            if (self.pageSize() > 200) self.pageSize(200);
            
            var form = {
                columnName: self.filterColumn(),
                filterType: self.filterType(),
                columnValue: self.filterValue(),
                sortColumn: self.sortColumn(),
                sortReverse: self.sortType() == 'DESC',
                dateColumn: self.filterDateColumn(),
                startDate: self.filterDateStart(),
                endDate: self.filterDateEnd(),
                entityTypeValue: "CO"
            };

            ajax.post('reportRequest', form).done(function (response) {
                util.notify.info("Your downloading has been started successfully. Please visit : " + response.message + " Or check your registred mail address");
            });
        };

        self.add = function () {
            window.location = '/contact/add';
        };

        self.filterColumns = ko.observableArray(['Name', 'FirstName','Email', 'Mobile', 'CompanyName']);
        self.filterTypes = ko.observableArray(['like', 'equal', 'exact', 'notequal', 'lessthan', 'lessorequal', 'greaterthan', 'greaterorequal', 'in', 'between']);
        self.sortColumns = ko.observableArray(['Name', 'FirstName', 'Email', 'Mobile', 'CompanyName', 'CreatedOn', 'ModifiedOn']);
        self.sortTypes = ko.observableArray(['ASC', 'DESC']);
        self.filterDateColumns = ko.observableArray(['CreatedOn', 'ModifiedOn']);

        self.filterColumn = ko.observable('Name');
        self.filterType = ko.observable('like');
        self.filterValue = ko.observable('%');
        self.sortColumn = ko.observable('ModifiedOn');
        self.sortType = ko.observable('DESC');
        self.filterDateColumn = ko.observable('CreatedOn');
        self.filterDateStart = ko.observable(util.date.min());
        self.filterDateEnd = ko.observable(util.date.now());

        self.pageIndex = ko.observable(1);
        self.pageSize = ko.observable(25);
        self.totalPages = ko.observable(0);
        self.totalRecords = ko.observable(0);

        self.search = function () {
            if (!self.filterColumn()) self.filterColumn('Name');
            if (!self.filterValue()) self.filterValue('%');
            if (self.pageIndex() <= 0) self.pageIndex(1);
            if (self.pageIndex() > self.totalPages()) self.pageIndex(self.totalPages());
            if (self.pageSize() < 25) self.pageSize(25);
            if (self.pageSize() > 200) self.pageSize(200);

            var form = {
                columnName: self.filterColumn(),
                filterType: self.filterType(),
                columnValue: self.filterValue(),
                sortColumn: self.sortColumn(),
                sortReverse: self.sortType() == 'DESC',
                dateColumn: self.filterDateColumn(),
                startDate: self.filterDateStart(),
                endDate: self.filterDateEnd(),
                page: self.pageIndex(),
                pageSize: self.pageSize()
            };

            ajax.get('contact', form)
                .done(function (response) {
                    self.contacts([]);
                    self.pageIndex(response.currentPage);
                    self.pageSize(response.itemsPerPage);
                    self.totalRecords(response.totalItems);
                    self.totalPages(response.totalPages);
                    $.each(response.items, function (row, a) {
                        var contact = new Contact(a);
                        self.contacts.push(contact);
                    });
                });
        };

        self.previousPage = function () {
            self.pageIndex(parseFloat(self.pageIndex()) - 1);
            self.search();
        };

        self.nextPage = function () {
            self.pageIndex(parseFloat(self.pageIndex()) + 1);
            self.search();
        };

        self.firstPage = function () {
            self.pageIndex(1);
            self.search();
        };

        self.lastPage = function () {
            self.pageIndex(self.totalPages());
            self.search();
        };

        self.SortItems = function (columnName) {
            var col = self.sortColumn();
            var sortType = self.sortType();
            if (col == columnName) {
                self.sortType(sortType == 'ASC' ? 'DESC' : 'ASC');
            }
            else {
                self.sortColumn(columnName);
                self.sortType('ASC');
            }
            self.pageIndex(1);
            self.search();
        };

        self.pageIndex(model.currentPage);
        self.pageSize(model.itemsPerPage);
        self.totalRecords(model.totalItems);
        self.totalPages(model.totalPages);
    };

    exports.exec = function (sectionId, model) {
        var viewModel = new ViewModel(model, sectionId.substring(0, 4) == "Ajax");
        ko.applyBindings(viewModel, document.getElementById(sectionId));
    };
    return exports;
});
